package top.stmo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 *     ---------------------解决中文乱码问题---------------------
 *
 *     post方式：
 *
 *      获取流之前设置流的字符编码集
 *      req.setCharacterEncoding("utf-8");
 *
 *     get方式：
 *      将数据以乱码的字符集转换为字符数组，再转换为utf-8字符串，即先解码，再编码
 *      new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
 *
 *      Tomcat8.0之后，已将GET请求乱码问题解决，设置默认的解码方式为UTF-8
 */
@WebServlet("/req3")
public class Request3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                                            throws ServletException, IOException {
        System.out.println("get");

        req.setCharacterEncoding("utf-8");

        Map<String, String[]> map = req.getParameterMap();
        for (String s : map.keySet()) {
            System.out.print(s + "：");
            String[] strings = map.get(s);
            for (String s1 : strings) {
                System.out.print(s1 + " ");
            }
            System.out.println();
        }

        System.out.println("---------------------");

        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            System.out.println(hobby);
        }

        System.out.println("---------------------");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username);
        System.out.println(password);

        String encode = URLEncoder.encode(username,"ISO-8859-1");
        String decode = URLDecoder.decode(encode,"UTF-8");
        System.out.println(decode);

        username = new String(username.getBytes(StandardCharsets.ISO_8859_1),
                                                        StandardCharsets.UTF_8);

        System.out.println(username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                                        throws ServletException, IOException {
       doGet(req,resp);
    }
}
